// @flow

const st = typeof localStorage === 'object' ? localStorage : {};

type Storage = {
  set(key: string, value: any): void,
  get(key: string): ?any,
  remove(key: string): void,
};

export const keys = {
  blog: '__mpan_blog__',
  auth: '__mpan_auth__',
  name: '__mpan_name__',
};

const storage: Storage = {
  setStr(key, value) {
    st[key] = value;
  },
  set(key, value) {
    st[key] = JSON.stringify(value);
  },
  getStr(key) {
    if (!st[key]) return null;
    const value = st[key];
    try {
      const parsed = value;
      return parsed;
    } catch (e) {
      return value;
    }
  },
  get(key) {
    if (!st[key]) return null;
    const value = st[key];
    try {
      const parsed = JSON.parse(value);
      return parsed;
    } catch (e) {
      return value;
    }
  },
  remove(key) {
    delete st[key];
  },
};

export default storage;
